package com.example.administrator.yuejian35.Find.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.speech.RecognizerIntent;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.yuejian35.Config;
import com.example.administrator.yuejian35.Find.FindModel;
import com.example.administrator.yuejian35.Find.adapter.CommentAdapter;
import com.example.administrator.yuejian35.Find.adapter.PostPicAdapter;
import com.example.administrator.yuejian35.Find.bean.Comment;
import com.example.administrator.yuejian35.Find.bean.Post;
import com.example.administrator.yuejian35.Find.bean.PostPic;
import com.example.administrator.yuejian35.Home.HomeModel;
import com.example.administrator.yuejian35.Home.activity.ActivitysActivity;
import com.example.administrator.yuejian35.Home.bean.Result;
import com.example.administrator.yuejian35.MainActivity;
import com.example.administrator.yuejian35.R;
import com.example.administrator.yuejian35.button.ShineButton;
import com.example.administrator.yuejian35.library.MaterialSearchView;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PostActivity extends AppCompatActivity {
    private Post post;
    private TextView uname,centent,time;
    private TextView mTitleView;
    private ImageView pic;
    private CircleImageView upic;
    private Context context;

    private ListView mListView;

    private View mHeadView;
    private View mFloatBarInLvHeader;
    private View mFloatBar;

    private CommentAdapter adapter;
    private PostPicAdapter postPicAdapter;

    private RecyclerView rv;

    private ImageButton post_btn_back;

    private MaterialSearchView searchView;

    private ShineButton shoucang;

    private String Uid,id,pid,name,notes;
    private String bbb="false";
    private String acid = "0";

    private SharedPreferences sp;
    private SharedPreferences.Editor editor1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        mTitleView = (TextView) findViewById(R.id.post_title);
        post_btn_back = (ImageButton) findViewById(R.id.post_btn_back);


        searchView = (MaterialSearchView) findViewById(R.id.search_view);
        searchView.setVoiceSearch(false);
        searchView.setCursorDrawable(R.drawable.color_cursor_white);
        searchView.setEllipsize(true);

        searchView.setOnQueryTextListener(new MaterialSearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                /*Snackbar.make(findViewById(R.id.activity_post), "Query: " + query, Snackbar.LENGTH_LONG)
                        .show();*/
                FindModel findModel = new FindModel();
                Call<Result> call = findModel.comment(pid,Uid,query);
                call.enqueue(new Callback<Result>() {
                    @Override
                    public void onResponse(Call<Result> call, Response<Result> response) {
                        if(response.body().getResult().equals("success")){
                            Toast.makeText(PostActivity.this,"发布成功！！！",Toast.LENGTH_SHORT).show();
                        }
                        else {
                            Toast.makeText(PostActivity.this,"发布失败！！！",Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<Result> call, Throwable t) {

                    }
                });
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                //Do some magic
                return false;
            }
        });

        searchView.setOnSearchViewListener(new MaterialSearchView.SearchViewListener() {
            @Override
            public void onSearchViewShown() {
                //Do some magic
            }

            @Override
            public void onSearchViewClosed() {
                //Do some magic
            }
        });

        post_btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        mListView = (ListView) findViewById(R.id.lv);
        context = this;

        // ListView 顶部隐藏的浮动栏

        mFloatBar = findViewById(R.id.float_bar);

        // ListView 第二个头部控件（效果图中的红色区域）
        mHeadView = LayoutInflater.from(context).inflate(R.layout.item_post_headview, mListView, false);
        mListView.addHeaderView(mHeadView);

        uname = (TextView) mHeadView.findViewById(R.id.post_uname);
        time = (TextView) mHeadView.findViewById(R.id.post_time);
        centent = (TextView) mHeadView.findViewById(R.id.post_content);
        upic = (CircleImageView) mHeadView.findViewById(R.id.me_upic);
        rv = (RecyclerView) mHeadView.findViewById(R.id.rv_post_pic);
        shoucang = (ShineButton) mHeadView.findViewById(R.id.post_btn_colle);
        // ListView 第三个头部控件（浮动栏）
        mFloatBarInLvHeader = LayoutInflater.from(context).inflate(R.layout.item_post_floatbar, mListView, false);
        mListView.addHeaderView(mFloatBarInLvHeader);

        post = getIntent().getParcelableExtra("post");

       if (post!=null){
            String postid = post.getPid();
            pid = postid;
           uname.setText(post.getUname());
           time.setText(post.getDate());
           centent.setText(post.getContent());

           if(!post.getUserpic().equals("")){
               Picasso.with(context)
                       .load(Config.CoachImages_URL+post.getUserpic())
                       .into(upic);
           }
        }
        Log.v("pid",pid);
        postpic();

        MainActivity mainActivity = new MainActivity();
        Uid = mainActivity.getUserId();

        FindModel findModel = new FindModel();
        Call call = findModel.commentlist(Integer.parseInt(post.getPid()));

        call.enqueue(new Callback<List<Comment>>() {

            @Override
            public void onResponse(Call<List<Comment>> call, Response<List<Comment>> response) {
                List<Comment> comments = response.body();
                //Toast.makeText(getActivity(), list.toString(), Toast.LENGTH_SHORT).show();
                adapter = new CommentAdapter(comments,PostActivity.this);
                mListView.setAdapter(adapter);
            }

            @Override
            public void onFailure(Call<List<Comment>> call, Throwable t) {

            }
        });

        sp = getSharedPreferences(Uid, Context.MODE_PRIVATE);
        editor1 = sp.edit();

        shoucang.setOnCheckStateChangeListener(new ShineButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(View view, final boolean checked) {
                //Log.e(TAG, "click " + checked);
                if(checked==true){
                    //final String aid =activitys.getAid();
                    FindModel findModel = new FindModel();
                    Call<Result> call = findModel.post_collect(pid,Uid,"true","");
                    call.enqueue(new Callback<Result>() {
                        @Override
                        public void onResponse(Call<Result> call, Response<Result> response) {
                            Toast.makeText(PostActivity.this,"收藏成功！！！",Toast.LENGTH_SHORT).show();
                            id = response.body().getResult();
                            editor1.putString("post_collect","true");
                            editor1.putString(pid,pid);
                            editor1.commit();

                        }

                        @Override
                        public void onFailure(Call<Result> call, Throwable t) {
                            Log.v("联网","失败！！！");
                        }
                    });
                }

                else if(checked==false){
                    //String aid =activitys.getAid();
                    FindModel findModel = new FindModel();
                    Call<Result> call = findModel.post_collect(pid,Uid,"false",id);
                    call.enqueue(new Callback<Result>() {
                        @Override
                        public void onResponse(Call<Result> call, Response<Result> response) {
                            Toast.makeText(PostActivity.this,"取消收藏成功！！！",Toast.LENGTH_SHORT).show();
                            //type = String.valueOf(checked);
                            editor1.putString("post_collect","false");
                            editor1.putString(pid,pid);
                            editor1.commit();
                        }

                        @Override
                        public void onFailure(Call<Result> call, Throwable t) {
                            Log.v("联网","失败！！！");
                        }
                    });

                }
            }

        });

        bbb = sp.getString("post_collect","-1");
        acid = sp.getString(pid,"-1");

        if(bbb.equals("true") && acid.equals(pid)){
            shoucang.setChecked(true);
        }


        mListView.setSelection(0);
        // 监听 ListView 滑动事件
        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                 /* 判断ListView头部中的浮动栏(mFloatBarInLvHeader)当前是否可见
                  * 来决定隐藏或显示浮动栏(mFloatBar)*/
                if (firstVisibleItem > 0) {
                    mTitleView.setText("skdjsjdlccc");
                } else {
                    mTitleView.setText("帖子正文");
                }

                if (firstVisibleItem >= 1) {
                    mFloatBar.setVisibility(View.VISIBLE);
                } else {
                    mFloatBar.setVisibility(View.GONE);
                }
            }
        });

    }

    private void postpic() {

        FindModel findmodel = new FindModel();
        Call callpic = findmodel.postpic(Integer.parseInt(post.getPid()));

        callpic.enqueue(new Callback<List<PostPic>>() {
            @Override
            public void onResponse(Call<List<PostPic>> call, Response<List<PostPic>> response) {

                List<PostPic> post = response.body();
                postPicAdapter = new PostPicAdapter(PostActivity.this, post);

                GridLayoutManager layoutManager = new GridLayoutManager(PostActivity.this,3);

                rv.setLayoutManager(layoutManager);
                rv.setAdapter(postPicAdapter);
                rv.setItemAnimator(new DefaultItemAnimator());

            }

            @Override
            public void onFailure(Call<List<PostPic>> call, Throwable t) {

            }
        });
    }

    /*提交框*/

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);

        MenuItem item = menu.findItem(R.id.action_search);
        searchView.setMenuItem(item);

        return true;
    }


}
